import React, { useEffect, useMemo, useState } from 'react'

type LogSummary = {
  id: number
  server_id: number
  started_at: string
  ended_at?: string | null
  bytes_count: number
}

type LogDetail = LogSummary & { content: string }

export function LogsModal({ serverId, onClose }: { serverId: number; onClose: () => void }): JSX.Element {
  const [list, setList] = useState<LogSummary[]>([])
  const [loading, setLoading] = useState(false)
  const [selected, setSelected] = useState<LogDetail | null>(null)
  const [query, setQuery] = useState('')

  const loadList = async () => {
    setLoading(true)
    try {
      const resp = await fetch(`/api/logs/?server_id=${serverId}`)
      const data = await resp.json()
      setList(data)
    } finally {
      setLoading(false)
    }
  }

  const loadDetail = async (id: number) => {
    const resp = await fetch(`/api/logs/${id}`)
    const data = await resp.json()
    setSelected(data)
  }

  useEffect(() => { loadList() }, [serverId])

  const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  const tokens = useMemo(() => query.trim().split(/\s+/).filter(Boolean), [query])
  const highlightRegex = useMemo(() => {
    if (!tokens.length) return null
    const pattern = tokens.map(escapeRegExp).join('|')
    try { return new RegExp(`(${pattern})`, 'gi') } catch { return null }
  }, [tokens])

  const highlighted = useMemo(() => {
    const text = selected?.content || ''
    if (!highlightRegex) return <>{text}</>
    const parts = text.split(highlightRegex)
    return parts.map((part, i) => highlightRegex.test(part)
      ? <mark key={i} style={{ background: 'rgba(59,130,246,0.35)', color: 'inherit', padding: 0 }}>{part}</mark>
      : <span key={i}>{part}</span>
    )
  }, [selected?.content, highlightRegex])

  const matchCount = useMemo(() => {
    if (!selected?.content || !highlightRegex) return 0
    const m = selected.content.match(highlightRegex)
    return m ? m.length : 0
  }, [selected?.content, highlightRegex])

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <div>会话日志</div>
          <button className="btn btn-sm" onClick={loadList}>刷新</button>
        </div>
        <div className="modal-body" style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 12 }}>
          <div className="panel" style={{ overflow: 'auto', maxHeight: '60vh' }}>
            <table className="table">
              <thead>
                <tr><th>ID</th><th>开始</th><th>字节</th></tr>
              </thead>
              <tbody>
                {list.map((r) => (
                  <tr key={r.id} onClick={() => loadDetail(r.id)} style={{ cursor: 'pointer' }}>
                    <td>{r.id}</td>
                    <td>{new Date(r.started_at).toLocaleString()}</td>
                    <td>{r.bytes_count}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="panel" style={{ display: 'grid', gridTemplateRows: 'auto 1fr auto', maxHeight: '60vh' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: 12, borderBottom: '1px solid var(--border)' }}>
              <input className="input" placeholder="关键字（空格分隔多个）" value={query} onChange={(e) => setQuery(e.target.value)} />
              {selected && (
                <>
                  <div className="muted">{matchCount} 个匹配</div>
                  <button className="btn btn-sm" onClick={async () => {
                    const resp = await fetch(`/api/logs/${selected.id}`)
                    const data: LogDetail = await resp.json()
                    const started = new Date(data.started_at).toISOString().replace(/[:.]/g, '-')
                    const filename = `log-${data.server_id}-${started}.txt`
                    const blob = new Blob([data.content || ''], { type: 'text/plain;charset=utf-8' })
                    const url = URL.createObjectURL(blob)
                    const a = document.createElement('a')
                    a.href = url
                    a.download = filename
                    document.body.appendChild(a)
                    a.click()
                    a.remove()
                    URL.revokeObjectURL(url)
                  }}>下载</button>
                </>
              )}
            </div>
            <div style={{ padding: 12, whiteSpace: 'pre-wrap', overflow: 'auto' }}>
              {selected ? highlighted : '选择左侧一条查看详情'}
            </div>
            <div style={{ padding: 10, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
              <button className="btn" onClick={() => setQuery('')}>清空搜索</button>
            </div>
          </div>
        </div>
        <div className="modal-foot" style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button className="btn" onClick={onClose}>关闭</button>
        </div>
      </div>
    </div>
  )
}

